import 'dart:async';

import 'package:example_flutter/models/chuck_categories.dart';
import 'package:example_flutter/networking/response.dart';
import 'package:example_flutter/repository/chuck_category_repository.dart';

class ChuckCategoryBloc {
  ChuckCategoryRepository _chuckCategoryRepository;
  StreamController _chuckListController;

  StreamSink<Response<ChuckCategories>> get chuckListSink => _chuckListController.sink;

  Stream<Response<ChuckCategories>> get chuckListStream => _chuckListController.stream;

  ChuckCategoryBloc() {
    _chuckCategoryRepository = ChuckCategoryRepository();
    _chuckListController = StreamController<Response<ChuckCategories>>();
    fetchCategories();
  }

  fetchCategories() async {
    chuckListSink.add(Response.loading('正在获取笑话类别列表！'));
    try {
      ChuckCategories chuckCategories = await _chuckCategoryRepository.fetchChuckCategoryData();
      chuckListSink.add(Response.completed(chuckCategories));
    } catch (e) {
      chuckListSink.add(Response.error(e.toString()));
      print(e);
    }
  }

  dispose() {
    _chuckListController?.close();
  }
}